package com.wn.ziroom.controller;


import com.wn.utils.*;
import com.wn.ziroom.entity.*;
import com.wn.ziroom.service.*;
import com.wn.ziroom.utils.JsonUtils;
import com.wn.ziroom.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangzhijia
 * @since 2023-02-23 02:27:54
 */
@Controller
@RequestMapping("/ziroom_portal/owner")
public class OwnerController {


    private IncomeorderService incomeorderService;

    private RoomService roomService;
    private StringRedisTemplate redisTemplate;
    private RabbitTemplate rabbitTemplate;
    private OwnerService ownerService;
    private QuartersService quartersService;
    @Autowired
    public void setRoomService(RoomService roomService) {
        this.roomService = roomService;
    }
    @Autowired
    public void setIncomeorderService(IncomeorderService incomeorderService) {
        this.incomeorderService = incomeorderService;
    }

    @Autowired
    public void setQuartersService(QuartersService quartersService) {
        this.quartersService = quartersService;
    }

    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setOwnerServiceService(OwnerService ownerService) {
        this.ownerService = ownerService;
    }


    @GetMapping("/login")
    public String login() {
        return "ownerLogin";
    }


    @PostMapping("/message")
    @ResponseBody
    public String message(@RequestParam("phone") String phone) throws ExecutionException, InterruptedException {
        /*-----------手机号是否被注册-----------*/
        Owner owner = ownerService.selectByPhoneNumber(phone);
        if (Objects.isNull(owner)) {
            ownerService.addOwner(phone);
        }
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        MessageUtils.snedMessage(phone, code);
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(phone, String.valueOf(code), 60, TimeUnit.SECONDS);
        return "发送成功";
    }

    @PostMapping("/ownerLogin")
    public String ownerLogin(Owner owner, @RequestParam("verifyCode") String verifyCode,  //-- 接收验证码
                             HttpServletResponse response,  //-- 响应对象。用于把token返回给客户端
                             Map<String, Object> map) {


        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

        /*检测验证码是否过期*/
        String value = opsForValue.get(owner.getPhone());
        if (value == null) {
            map.put("error_msg", "验证码有效期60秒，已过期");
            return "ownerLogin";
        }

        /*检查验证码是否正确*/
        if (!Objects.equals(verifyCode, value)) {
            map.put("error_msg", "验证码不正确");
            return "ownerLogin";
        }

        /*登录成功后从redis中移除*/
        redisTemplate.delete("phone");
        String token = JwtUtils.createToken(owner, 1800 * 60 * 1000);
        //-- 2.把token放到Cookie中
        CookieUtils.setCookie("token", token, response);
        //-- 3.把token放入redis中
        opsForValue.set(token, token, 3600 * 60 * 1000, TimeUnit.MILLISECONDS);
        String ownerName = owner.getOwnerName();
        map.put("Name",ownerName);
        return "OwnerInfo";


    }

    @GetMapping("/onwerInfo")
    public String onwerInfo() {

        return "OwnerInfo";

    }

    @GetMapping("/goToRent")
    public String goToRent(Model model) {
       List<Quarters> quartersList= quartersService.selectall();
        model.addAttribute("quartersList",quartersList);
        return "rentHouse";
    }
    @GetMapping("/goToIntroduce")
    public String goToIntroduce() {

        return "OwnerIntroduce";

    }
    @GetMapping("/goToMyHouse")
    public String goToHouse(Model model,HttpServletRequest request) {
        String token = CookieUtils.getCookie("token", request);
        Owner owner = JwtUtils.verifyTokenWithoutVerifyExp(token, Owner.class);
        owner = ownerService.selectByPhoneNumber(owner.getPhone());

        List<RoomVoo> roomList = roomService.selectRoomVooById(owner.getId());
        model.addAttribute("roomList",roomList);


        List<RoomVvo> roomUserList =roomService.selectRoomVvoById(owner.getId());
        model.addAttribute("roomUserList",roomUserList);

        return "OnwerHouse";

    }
    @GetMapping("/goToIncome")
    public String goToIncome(Model model,HttpServletRequest request) {
        String token = CookieUtils.getCookie("token", request);
        Owner owner = JwtUtils.verifyTokenWithoutVerifyExp(token, Owner.class);
        owner = ownerService.selectByPhoneNumber(owner.getPhone());
        List<Room> roomList=roomService.selectById(owner.getId());
        List<IncomeorderVo> incomeorderList=incomeorderService.selectByID(owner.getId());
        for (IncomeorderVo incomeorderVo : incomeorderList) {
            if (incomeorderVo.getEndTime().getTime()<new Date().getTime()){
                incomeorderVo.setStatus(1);
            }
        }
        model.addAttribute("incomeorderList",incomeorderList);
        model.addAttribute("roomList",roomList);
        return "OwnerIncome";

    }
    @GetMapping("/goToOrder")
    public String goToOrder() {

        return "OnwerOrder";

    }

    @PostMapping("/goToContract")
    public String goToContrast(RentHouseVo rentHouseVo,Model model, HttpServletRequest request) {
        System.out.println(rentHouseVo);
        /*-----------拿到业主id判----------*/
        String token = CookieUtils.getCookie("token", request);
        Owner owner = JwtUtils.verifyTokenWithoutVerifyExp(token, Owner.class);
        owner = ownerService.selectByPhoneNumber(owner.getPhone());
        /*----------完善信息--------------*/

        Quarters quarters =quartersService.selectByQname(rentHouseVo.getQuartername());
        rentHouseVo.setName(quarters.getName());
        model.addAttribute("owner",owner);
        model.addAttribute("rentHouseVo",rentHouseVo);

        String s = JsonUtils.toJsonStr(rentHouseVo);
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(owner.getPhone()+"rentHouseVo",s);
        return "confirmationInformation";

    }

    @PostMapping("/goToPay")
    public String goToContrast(SignVo signVo, Model model, HttpServletRequest request ,RedirectAttributes attributes) {
        System.out.println(signVo);
        /*-----------拿到业主id和价格信息----------*/
        String token = CookieUtils.getCookie("token", request);
        Owner owner = JwtUtils.verifyTokenWithoutVerifyExp(token, Owner.class);
        owner = ownerService.selectByPhoneNumber(owner.getPhone());
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(owner.getPhone()+"signVo",JsonUtils.toJsonStr(signVo));
        String s = opsForValue.get(owner.getPhone() + "rentHouseVo");
        /*----------完善信息修改业主信息--------------*/
        owner.setOwnerName(signVo.getOwnername());
        owner.setPhone(signVo.getPhone());
        owner.setAddressId(1);
        owner.setIdentity(signVo.getIdentity());
        owner.setBankNum(signVo.getBanknum());
        /*-----------完善房源信息----------------*/
        long time = System.currentTimeMillis();
        int years = signVo.getYears();
        time = time+(years*31536000000L);
        Date date = new Date();
        date.setTime(time);
        owner.setSigningTime(new Date());
        owner.setExpirationTime(date);
        System.out.println(owner);
        ownerService.updateById(owner);
        /*---------拿到价格------------*/
        RentHouseVo rentHouseVo = JsonUtils.toObject(s,RentHouseVo.class);
        long l = SnowFlowUtils.getInstance().nextId();
        attributes.addAttribute("WIDout_trade_no",l);
        attributes.addAttribute("WIDtotal_amount",rentHouseVo.getEngineeringPrice());
        attributes.addAttribute("WIDsubject","自如");
        attributes.addAttribute("WIDbody","自如");


        return "redirect:/payHouse";

    }



}

